<?php

namespace app\common\model;

use app\common\service\StatusService;
use think\Db;
use think\Model;


class Address extends Model
{

    

    

    // 表名
    protected $name = 'address';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
	    'status_text'
    ];
	
	
	public function user()
	{
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function province()
	{
		return $this->belongsTo('area', 'province_id', 'id', '', 'left')->setEagerlyType(0);
	}
	public function city()
	{
		return $this->belongsTo('area', 'city_id', 'id', '', 'left')->setEagerlyType(0);
	}
	public function area()
	{
		return $this->belongsTo('area', 'area_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = StatusService::$goodsSpecStatusList;
		return $list[$value] ??'';
	}


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
	
	public function getUserAddress($userId)
	{
		return Db::name('address')->alias('a')
			->join('area p', 'a.province_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area aa', 'a.area_id = aa.id', 'left')
			->where(['a.user_id' => $userId, 'status' => StatusService::STATUS_NORMAL])
			->field('a.id, a.name, a.mobile, a.province_id, a.city_id, a.area_id, a.address, a.is_default, p.name as province_name, c.name as city_name, aa.name as area_name')
			->order(['update_time' => 'desc'])
			->select();
	}
	
	protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
